package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.DateData;
import com.lzx.iteam.bean.SalaryFieldBean;
import com.lzx.iteam.bean.SalaryMemberSalaryBean;
import com.lzx.iteam.bean.SalaryRuleBean;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMemberSalaryMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.net.WithoutObjMsg;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.CHScrollFieldView;
import com.lzx.iteam.widget.CHScrollWXYJView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.*;

import static android.media.CamcorderProfile.get;
import static com.lzx.iteam.DialerApp.mContext;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2017年 01月 11日
 * Time: 上午10:29
 *
 * @QQ : 1234567890
 * **********************************
 *
 * 设置基本工资 和 自定义字段 数据 页面
 */
public class SalaryFieldFormActivity extends MyBaseActivity {

    @FindViewById(id = R.id.ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.tv_title_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.tv_title_right2)
    private TextView mTvEdit;
    @FindViewById(id = R.id.tv_title_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.ch_scroll_excle_item)
    private CHScrollFieldView mScrollViewField;
    @FindViewById(id = R.id.ll_excle_item)
    private LinearLayout mLayoutField;
    @FindViewById(id = R.id.lv_field_excle)
    private ListView mListView;


    //方便测试，直接写的public
    public HorizontalScrollView mTouchView;
    private List<CHScrollFieldView> mHScrollViews = new ArrayList<>();
    private Map<String,Object> mData;
    private ArrayList<SalaryMemberSalaryBean> mMemberSalary = new ArrayList<>();
    private ArrayList<SalaryFieldBean> mMemberField;
    private MyAdapter mAdapter;
    private SalaryRuleBean mRuleData;

    private String mGroupId;
    private DateData mSelectDate;
    private int mPositionX = -1;
    private int mPositionY = -1;

    private final int GET_SALARYS = 3000;
    private final int SET_SALARYS = 3001;
    private final int TO_EDIT_FIELD = 4000;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            waitDlgDismiss();
            if (msg.arg1 == 0){
                switch (msg.what){
                    case GET_SALARYS:
                        mData = (Map<String, Object>) msg.obj;
                        mMemberSalary = (ArrayList<SalaryMemberSalaryBean>) mData.get("salary");
                        mMemberField = (ArrayList<SalaryFieldBean>) mData.get("field");
                        setData();
                        break;
                    case SET_SALARYS:
                        Intent step = new Intent(mActivity, SalaryCalculateActivity.class);
                        step.putExtra("group_id",mGroupId);
                        step.putExtra("salary_rule",mRuleData);
                        step.putExtra("member_salary",mMemberSalary);
                        step.putExtra("member_salary_fileds",mMemberField);
                        step.putExtra("month",mSelectDate);
                        startActivity(step);
                        break;
                }
            }else{
                Toast.makeText(mActivity, (String) msg.obj,
                      Toast.LENGTH_LONG).show();
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState,R.layout.salary_field_form_layout);
    }

    @Override
    public void initListener() {

        mLayoutBack.setOnClickListener(this);
        mTvRight.setOnClickListener(this);
        mTvEdit.setOnClickListener(this);
    }

    @Override
    public void initData() {

        mTvTitle.setText("填写基本工资");
        mTvRight.setText("下一步");
        mTvEdit.setText("编辑字段");
        mTvEdit.setVisibility(View.VISIBLE);

        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mRuleData = (SalaryRuleBean) intent.getSerializableExtra("salary_rule");
        mSelectDate = (DateData) intent.getSerializableExtra("month");
        getSalarys();

    }

    /**
     * 设置标题
     */
    private void setTitleData(){
        mLayoutField.removeAllViews();
        for (int i = 0; i < mMemberField.size(); i++) {
            TextView tv = new TextView(this);
            //Constants.dip2px(this, 79.4f)
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Constants.dip2px(this, 79.4f), ViewGroup.LayoutParams.MATCH_PARENT);
            tv.setGravity(Gravity.CENTER);
            tv.setLayoutParams(params);
            tv.setText(mMemberField.get(i).getName());
            tv.setTextColor(getResources().getColor(R.color.black));
            mLayoutField.addView(tv);
            View line = new View(mActivity);
            LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 0.6f), ViewGroup.LayoutParams.MATCH_PARENT);
            line.setLayoutParams(lineParams);
            line.setBackgroundResource(R.color.excle_line);
            mLayoutField.addView(line);
        }
    }

    /**
     * 设置列表数据
     */
    private void setData(){
        if (mMemberSalary == null) {
            mMemberSalary = new ArrayList<>();
        }
        if (mMemberSalary.size() == 0){
            showShortToast("没有数据");
        }else{

            for (int i = 0; i < mMemberSalary.size(); i++) {
                SalaryMemberSalaryBean salaryBean = mMemberSalary.get(i);
                LinkedHashMap<String,SalaryFieldBean> map = new LinkedHashMap<>();
                map.put("基本工资",new SalaryFieldBean("基本工资",salaryBean.getBase_salary()));
                if (salaryBean.getSalary_fields() == null){
                    map.put("岗位津贴",new SalaryFieldBean("岗位津贴"));
                    map.put("奖金",new SalaryFieldBean("奖金"));
                } else{
                    for (int j = 0; j < salaryBean.getSalary_fields().length; j++) {
                        SalaryFieldBean field = salaryBean.getSalary_fields()[j];
                        map.put(field.getName(),field);
                    }
                }
                mMemberSalary.get(i).setFieldList(map);
            }

            if (mMemberField == null){
                mMemberField = new ArrayList<>();
                mMemberField.add(new SalaryFieldBean("基本工资"));
                mMemberField.add(new SalaryFieldBean(1,"岗位津贴"));
                mMemberField.add(new SalaryFieldBean(2,"奖金"));
            }else{
                mMemberField.add(0,new SalaryFieldBean("基本工资"));
            }
            setTitleData();
        }
        mAdapter = new MyAdapter();
        mListView.setAdapter(mAdapter);
        mAdapter.bindData(mMemberSalary);

    }

    /**
     * 滑动中
     * @param l
     * @param t
     * @param oldl
     * @param oldt
     */
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        for (CHScrollFieldView scrollView : mHScrollViews) {
            if (mTouchView != scrollView)
                scrollView.smoothScrollTo(l, t);
        }

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_title_right2:
                Intent fieldEdit = new Intent(mActivity,SalaryFieldEditActivity.class);
                fieldEdit.putExtra("group_id",mGroupId);
                fieldEdit.putExtra("salary_field",mMemberField);
                startActivityForResult(fieldEdit,TO_EDIT_FIELD);
                break;
            case R.id.tv_title_right:
                saveListData();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case TO_EDIT_FIELD:
                    mMemberField = (ArrayList<SalaryFieldBean>) data.getSerializableExtra("salary_rule");
                    setTitleData();
                    mAdapter.bindData(mMemberSalary);
                    break;
            }
        }
    }

    /**
     * 编辑框
     * @param title
     */
    public void showEditDialogMsg(String title,String content) {
        String okText = "确定";
        String cancelText = this.getString(R.string.cancel);
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(mActivity);

        mDialogUtil.salaryEditStyle(title,content,okText,cancelText,null,0);
        mDialogUtil.setOnEditDialogListener(new AllDialogUtil.EditDialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog, EditText ed) {
                String number = ed.getEditableText().toString().trim();
                upDateListData(number);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog, EditText ed) {
                lDialog.dismiss();
            }
        });

    }

    /**
     * 更新列表
     * @param number
     */
    private void upDateListData (String number){
        if (StringUtil.isEmpty(number)){
            number = "0";
        }
        String name = mMemberField.get(mPositionX).getName();
        if (mMemberSalary.get(mPositionY).getFieldList().get(name) == null){
            mMemberSalary.get(mPositionY).getFieldList().put(name,new SalaryFieldBean(name,number));
        } else{
            mMemberSalary.get(mPositionY).getFieldList().get(name).setMoney(number);
        }
        mAdapter.bindData(mMemberSalary);

    }

    /**
     * 保存基本信息
     */
    private void saveListData(){

        JSONArray member_salary = new JSONArray();
        try {
            for (int i = 0; i < mMemberSalary.size(); i++) {
                SalaryMemberSalaryBean member = mMemberSalary.get(i);
                Map<String,SalaryFieldBean> fieldList = member.getFieldList();
                JSONObject object = new JSONObject();
                object.put("attendance_id",member.get_id());
                object.put("base_salary",fieldList.get("基本工资").getMoney());

                JSONArray salary_fields = new JSONArray();

                LinkedHashMap<String,SalaryFieldBean> fields = new LinkedHashMap<>();
                fields.put("基本工资",fieldList.get("基本工资"));

                if (mMemberField.size() > 1){
                    for (int j = 1; j < mMemberField.size(); j++) {
                        SalaryFieldBean bean = fieldList.get(mMemberField.get(j).getName());
                        JSONObject field = new JSONObject();
                        if (bean == null) {
                            bean = new SalaryFieldBean(j,mMemberField.get(j).getName());
                            bean.setMoney("0");
                        }
                        fields.put(bean.getName(),bean);

                        field.put("order",j);
                        field.put("name",bean.getName());
                        field.put("money",bean.getMoney());
                        salary_fields.put(field);
                    }
                }
                // 修改当前页面的数据
                mMemberSalary.get(i).setFieldList(fields);

                object.put("salary_fields",salary_fields);
                member_salary.put(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        setSalarys(member_salary.toString());

    }


    /**
     * 获取成员基本工资和自定义字段
     */
    private void getSalarys(){
        waitDlgShow();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        GetMemberSalaryMsg msg = new GetMemberSalaryMsg(mHandler.obtainMessage(GET_SALARYS));
        msg.mApi = AsynHttpClient.API_SALARY_GET_SALARY;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    /**
     * 设置基本工资和自定义字段
     */
    private void setSalarys(String member_salary){
        waitDlgShow();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MEMBER_SALARY, member_salary));
        WithoutObjMsg msg = new WithoutObjMsg(mHandler.obtainMessage(SET_SALARYS));
        msg.mApi = AsynHttpClient.API_SALARY_SET_SALARY;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }


    class MyAdapter extends BaseAdapter{

        private ArrayList<SalaryMemberSalaryBean> mdata;

        public MyAdapter(){

        }

        public void bindData(ArrayList<SalaryMemberSalaryBean> data){
            this.mdata = data;
            notifyDataSetChanged();
        }
        @Override
        public int getCount() {
            return mdata == null ? 0:mdata.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            if(convertView == null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.salary_field_item_layout,null);
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_excle_item);
                holder.layoutScroll = (CHScrollFieldView) convertView.findViewById(R.id.ch_scroll_excle_item);
                holder.layoutSub = (LinearLayout) convertView.findViewById(R.id.ll_excle_item);
                convertView.setTag(holder);

            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            if (position%2 == 0){
                convertView.setBackgroundResource(R.color.excle_bg);
            }else{
                convertView.setBackgroundResource(R.color.white);
            }

            SalaryMemberSalaryBean bean = mdata.get(position);
            Map<String,SalaryFieldBean> fields = bean.getFieldList();

            holder.tvName.setText(bean.getUser_name());
            holder.layoutSub.removeAllViews();
            for (int i = 0; i < mMemberField.size(); i++) {
                TextView tv = new TextView(mContext);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 79.4f), ViewGroup.LayoutParams.MATCH_PARENT);
                tv.setGravity(Gravity.CENTER);
                tv.setLayoutParams(params);
                tv.setTextColor(getResources().getColor(R.color.black));

                SalaryFieldBean field = fields.get(mMemberField.get(i).getName());
                if (field == null) {
                    tv.setText("0");
                }else{
                    tv.setText(field.getMoney());
                }
                tv.setOnClickListener(new MyClickLinstener(i,position));
                holder.layoutSub.addView(tv);
                View line = new View(mActivity);
                LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 0.6f), ViewGroup.LayoutParams.MATCH_PARENT);
                line.setLayoutParams(lineParams);
                line.setBackgroundResource(R.color.excle_line);
                holder.layoutSub.addView(line);

            }
            if (!mHScrollViews.isEmpty()) {
                int size = mHScrollViews.size();
                final int scrollX = mScrollViewField.getScrollX();
                //第一次满屏后，向下滑动，有一条数据在开始时未加入
                if (scrollX != 0) {
                    final ViewHolder finalHolder = holder;
                    mListView.post(new Runnable() {
                        @Override
                        public void run() {
                            //当listView刷新完成之后，把该条移动到最终位置
                            finalHolder.layoutScroll.scrollTo(scrollX, 0);
                        }
                    });
                }
            }
            mHScrollViews.add(holder.layoutScroll);

            return convertView;
        }

        class ViewHolder{
            private TextView tvName;
            private LinearLayout layoutSub;
            private CHScrollFieldView layoutScroll;
        }

        class MyClickLinstener implements View.OnClickListener {

            private int y_position;    // x 列数
            private int x_position;    // y 行数
            private String content;    // 内容

            public MyClickLinstener(int x_position,int y_position) {
                this.x_position = x_position;
                this.y_position = y_position;
            }

            public MyClickLinstener(int x_position,int y_position,String content) {
                this.x_position = x_position;
                this.y_position = y_position;
                this.content = content;
            }

            @Override
            public void onClick(View view) {
                mPositionX = x_position;
                mPositionY = y_position;
                if ("0".equals(content) || "0.0".equals(content)){
                    content = "";
                }
                showEditDialogMsg(mMemberField.get(x_position).getName(),content);

            }
        }


    }
}
